<?php
// $Id: simple_cart.admin.inc,v 1.2 2011/01/25 18:16:14 vladsavitsky Exp $
/*
 * @file
 * simple_cart.admin.inc Contains admin's settings page
 */

/**
 * Menu callback to configure cart settings.
 */
function simple_cart_admin_form() {
  $form = array();

  $path = drupal_get_path('module', 'simple_cart');
  drupal_add_css($path . '/simple_cart.css');
  drupal_add_js($path . '/simple_cart_admin.js');

  $form['description_for_node_types_select'] = array(
    '#value' => t("Below you can select nodes of which content type can be added to cart (cartable nodes).
                  Listed content types has at least one field provided by CCK Money module so if you want 
                  to use some content type you should add field that will contain node's price."));
  $node_types = node_get_types('types');
  foreach ($node_types as $type => $type_data) {
    $form['simple_cart_is_cartable_' . $type] = array(
      '#type'           => 'checkbox',
      '#title'          => $type_data->name,
      '#default_value'  => variable_get('simple_cart_is_cartable_' . $type, ''),
      '#description'    => t("This content type doesn't have fields provided by Money CCK field module. Add this price-field to use this content type."),
      '#disabled'       => TRUE,
      '#attributes'     => array('class' => 'simple_cart_content_type_selector'),
    );
    $node_type_money_fields = _simple_cart_fields_by_type($type);
    if (count($node_type_money_fields) > 0) {
      unset($form['simple_cart_is_cartable_' . $type]['#disabled']);
      unset($form['simple_cart_is_cartable_' . $type]['#description']);
      $node_type_money_fields = array(0 => t('None')) + $node_type_money_fields;
      $form[$type] = array(
        '#type'           => 'fieldset',
        '#title'          => t("Price settings for %type", array('%type' => $type)),
        //'#description'    => t('Select field that contains a price for the node of this content type.'),
        '#collapsible'    => TRUE,
        '#collapsed'      => TRUE,
        '#attributes'     => array('id' => 'edit-simple-cart-is-cartable-' . $type . '-fieldset'),
      );
      $form[$type]['simple_cart_price_field_' . $type] = array(
        '#type'           => 'select',
        '#title'          => t("Price field"),
        '#options'        => $node_type_money_fields,
        '#default_value'  => variable_get('simple_cart_price_field_' . $type, ""),
        '#description'    => t("If price field was not selected than nodes of this type couldn't be added to cart and 'Add to Cart' link will not be shown."),
        '#required'       => TRUE,
        '#attributes'     => array('class' => 'simple_cart_price_field'),
      );
      $form[$type]['add_to_cart'] = array(
        '#type'           => 'fieldset',
        '#title'          => t("'Add to Cart' link"),
        '#collapsible'    => TRUE,
        '#collapsed'      => FALSE,
        '#attributes'     => array('class' => 'simple_cart_add_to_cart_fieldset'),
      );
      $form[$type]['add_to_cart']['simple_cart_show_add_to_cart_button_' . $type] = array(
        '#type'           => 'checkbox',
        '#title'          => t("Place 'Add to Cart' link into node's links"),
        '#description'    => t('You can disable this link and use your own way to add this button to page. Read simple_cart.api.inc file for more information.'),
        '#default_value'  => variable_get('simple_cart_show_add_to_cart_button_' . $type, FALSE),
      );
      $form[$type]['add_to_cart']['simple_cart_add_to_cart_button_text_' . $type] = array(
        '#type'           => 'textfield',
        '#title'          => t("Text that will be used for 'Add to Cart' link"),
        '#description'    => t("Default is 'Add to Cart' but you can set any text you like."),
        '#default_value'  => variable_get('simple_cart_add_to_cart_button_text_' . $type, t('Add to Cart')),
        // This field is required to avoid cases when link is shown with empty anchor:
        '#required'       => TRUE,
      );
    }
  }

  return system_settings_form($form);
}

//=============================================================================

/**
 * Menu callback to configure cart settings.
 */
function simple_cart_admin_email_form() {
  $form = array();

  $form['simple_cart_manager_emails'] = array(
    '#type'           => 'textarea',
    '#title'          => t("Manager emails"),
    '#description'    => t('Provide emails which will recieve email notifications when customer submit checkout page.'),
    '#default_value'  => variable_get('simple_cart_manager_emails', ''),
    '#required'       => TRUE,
    '#rows'           => 4,
  );
  // Customer's email template:
  $form['simple_cart_mail_to_customer'] = array(
    '#type'         => 'fieldset',
    '#title'        => t("Customer's notification email settings"),
    '#description'  => t('Customer will recieve email when checkout form was submitted. Below you can customize this message.'),
    '#collapsible'  => TRUE,
    '#collapsed'    => FALSE,
  );
  $form['simple_cart_mail_to_customer']['simple_cart_customer_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Customer Email Subject'),
    '#description' => t("The subject of the email. Allowed variables:") . ' ' .
    _simple_cart_build_token_list('customer', 'subject'),
    '#default_value' => variable_get('simple_cart_customer_subject', "Your order at !sitename"),
    '#required' => TRUE,
  );
  $form['simple_cart_mail_to_customer']['simple_cart_customer_body'] = array(
    '#type' => 'textarea',
    '#title' => t('Customer Email body'),
    '#description' => t('This will be the text of the email body. Allowed variables:') . ' ' .
    _simple_cart_build_token_list('customer', 'body'),
    '#default_value' => variable_get('simple_cart_customer_body', t("Hello @customers_name!\n\n You have ordered recently at !sitename this items:\n\n!items_list\n\nOur managers was recieved your order and process it as soon as posible.")),
    '#required' => TRUE,
  );
   // Manager's email template:
  $form['simple_cart_mail_to_manager'] = array(
    '#type'         => 'fieldset',
    '#title'        => t("Manager's notification email settings"),
    '#description'  => t('Manager will recieve email when checkout form was submitted. Below you can customize this message.'),
    '#collapsible'  => TRUE,
    '#collapsed'    => FALSE,
  );
  $form['simple_cart_mail_to_manager']['simple_cart_manager_subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Manager Email Subject'),
    '#description' => t('The subject of the email. Allowed variables:') . ' ' .
    _simple_cart_build_token_list('manager', 'subject'),
    '#default_value' => variable_get('simple_cart_manager_subject', "Order at !sitename"),
    '#required' => TRUE,
  );
  $form['simple_cart_mail_to_manager']['simple_cart_manager_body'] = array(
    '#type' => 'textarea',
    '#title' => t('Manager Email body'),
    '#description' => t('This will be the text of the email body. Allowed variables:') . ' ' .
    _simple_cart_build_token_list('manager', 'body'),
    '#default_value' => variable_get('simple_cart_manager_body', t("Customer @customers_name have ordered at !sitename this items:\n\n!items_list\n\nCustomer provide this contact information:\n\nName: @customers_name\n\nEmail: @customers_email\n\nPhone: @customers_phone\n\nCustomers comment:\n\n------------------------------\n\n@customers_comment\n\n------------------------------\n\n\n\n.")),
    '#required' => TRUE,
  );
  $form['#submit'][] = 'simple_cart_admin_email_form_submit';
  $form['#validate'][] = 'simple_cart_admin_email_form_validate';

  return system_settings_form($form);
}

/**
 * Validation handler for admin settings form.
 */
function simple_cart_admin_email_form_validate($form, &$form_state) {
  // Check manager's emails:
  if (!empty($form_state['values']['simple_cart_manager_emails'])) {
    $valid = array();
    $invalid = array();
    foreach (explode("\n", trim($form_state['values']['simple_cart_manager_emails'])) as $email) {
      $email = trim($email);
      if (!empty($email)) {
        if (valid_email_address($email)) {
          $valid[] = $email;
        }
        else {
          $invalid[] = $email;
        }
      }
    }
    if (empty($invalid)) {
      $form_state['manager_emails'] = $valid;
    }
    elseif (count($invalid) == 1) {
      form_set_error('simple_cart_manager_emails', t('%email is not a valid e-mail address.', array('%email' => reset($invalid))));
    }
    else {
      form_set_error('simple_cart_manager_emails', t('%emails are not valid e-mail addresses.', array('%emails' => implode(', ', $invalid))));
    }
  }
}

/**
 * Submit handler for the settings tab.
 */
function simple_cart_admin_email_form_submit($form, $form_state) {
  $op = $form_state['values']['op'];
  if ($op == t('Reset to defaults')) {
    unset($form_state['manager_emails']);
  }
  else {
    if (empty($form_state['manager_emails'])) {
      variable_del('simple_cart_manager_emails');
    }
    else {
      variable_set('simple_cart_manager_emails', $form_state['manager_emails']);
    }
    unset($form_state['manager_emails']);
    unset($form_state['values']['simple_cart_manager_emails']);
  }
}

//=============================================================================
/**
 * Returns an array of content types and related fields
 *
 * @staticvar array $fields_by_type
 * @param srting $type
 * @return array
 */
function _simple_cart_fields_by_type($type='') {
  if ($type) {
    $fields_by_type = array();
    if (function_exists('_content_type_info')) {
      $type_info = _content_type_info();
      foreach ($type_info['content types'] as $type_name => $type_data) {
        foreach ($type_data['fields'] as $field) {
          if ($field['type'] == 'money') {
            $fields_by_type[$type_name][$field['field_name']] = $field['widget']['label'] . ' (' . $field['field_name'] . ')';
          }
        }
      }
    }
    if (isset($fields_by_type[$type])) {
      return $fields_by_type[$type];
    }
  }
}

/**
 * Builds HTML-list of available tokens.
 * This list will be shown at module's settings page so it's not nessecary to
 * use theme function for this list.
 *
 * @param string $recipient Email recipient. Can be 'customer' or 'manager'
 * @param string $field Email field to which will be applied this tokens. Can be 'subject' or 'body'.
 * @return string Returns rendered HTML-list of tokens.
 */
function _simple_cart_build_token_list($recipient='customer', $field='body') {
  $common_tokens = array(
    '@customers_name'     => t("Customer's name"),
    '@customers_email'    => t("Customer's e-mail"),
    '@customers_phone'    => t("Customer's phone number"),
    '@customers_comment'  => t("Customer's comment to order"),
    '!sitename'           => t("Site name"),
    '!items_list'         => t("List of cart items"),
  );
  // Later we will create different tokens.
  $token_list['customer']['subject'] = $common_tokens;
  $token_list['customer']['body'] = $common_tokens;
  $token_list['manager']['subject'] = $common_tokens;
  $token_list['manager']['body'] = $common_tokens;
  $output = '';
  if (is_array($token_list[$recipient][$field]) and count($token_list[$recipient][$field])) {
    foreach ($token_list[$recipient][$field] as $key => $value) {
      $output .= '<li><em>' . $key .'</em> = ' . $value . ',</li>';
    }
  }
  return '<ul>' . $output . '</ul>';
}
